package com.lm.xmldemo01;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Iterator;
import java.util.List;

public class XmlTest {
    public static void main(String[] args) throws DocumentException {
        // 1. 创建SAXReader对象
        SAXReader reader = new SAXReader();

        // 2. 读取XML文件（示例文件路径需替换为实际路径）
        InputStream is = XmlTest.class.getClassLoader()
                .getResourceAsStream("students.xml");
        Document document = reader.read(is);

        // 3. 获取根节点
        Element root = document.getRootElement();
        System.out.println("根节点名称: " + root.getName());

        // 4. 遍历子节点
        List<Element> students = root.elements("Student");
        for (Element student : students) {
            // 获取属性值
            String no = student.attributeValue("No");
            System.out.println(MessageFormat.format("\n========学生No-->{0}===========",no));
            // 获取子节点内容
            String id = student.elementText("Id");
            System.out.println("学生ID: " + id);
            String name = student.elementText("Name");
            String age = student.elementText("Age");
            System.out.println("姓名: " + name);
            System.out.println("年龄: " + age);
        }
    }
}
